package top.lyc829.zzl_android.ui.regist;

import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.os.Handler;

import com.xuexiang.xui.utils.CountDownButtonHelper;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityRegistBinding;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.util.FormatUtil;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.BaseActivity;

public class RegistActivity extends BaseActivity {

    ActivityRegistBinding binding;

    private Handler handler = new Handler();

    private CountDownButtonHelper mCountDownHelper;
    private RegistViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRegistBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mViewModel = new ViewModelProvider(this).get(RegistViewModel.class);
        // 点击返回箭头返回上一页
        binding.mTitleBarRegist.setLeftClickListener(v -> finish());

        mCountDownHelper = new CountDownButtonHelper(binding.btSendCode, 60);


        binding.btSendCode.setOnClickListener(v -> {
            String email = binding.etRegistEmail.getText().toString().trim();
            if (!FormatUtil.isEmail(email)) {
                Utils.showToast("邮箱格式错误");
                return;
            }
            mViewModel.sendCode(email);
            mCountDownHelper.start();
        });

        mViewModel.getVerifyCodeLiveData().observe(this, s -> {
            if (Utils.isStringEmpty(s) || "-1".equals(s)) {
                Utils.showToast("验证码发送失败");
            } else {
                Utils.showToast("验证码发送成功");
            }
        });

        // 点击文字后弹窗显示用户协议
        binding.tvUserAgreement.setOnClickListener(v -> {
            new MaterialDialog.Builder(this)
                    .title("用户协议")
                    .content(R.string.user_agreement_detail)
                    .positiveText("关闭")
                    .show();
        });

        // 注册按钮的点击事件
        binding.btnRegist.setOnClickListener(v -> {
            if (!binding.cbxUserAgreement.isChecked()) {
                Utils.showToast("请勾选用户协议");
                return;
            }
            String account = binding.etRegistEmail.getText().toString().trim();
            String password = binding.etRegistPassword.getText().toString().trim();
            String verifyCode = binding.etRegistCode.getText().toString().trim();
            if (Utils.isStringEmpty(account) || Utils.isStringEmpty(password)) {
                Utils.showToast("用户名或密码为空");
                return;
            }

            if (!FormatUtil.isEmail(account)) {
                Utils.showToast("邮箱格式错误");
                return;
            }

            String realVerifyCode = mViewModel.getVerifyCodeLiveData().getValue();
            if (Utils.isStringEmpty(verifyCode)) {
                Utils.showToast("验证码为空");
                return;
            } else if (Utils.isStringEmpty(realVerifyCode)) {
                Utils.showToast("请先获取验证码");
                return;
            }

            if (!FormatUtil.isPassword(password)) {
                Utils.showToast("密码过于简单，请重新设置");
                return;
            }

            doRegist(account, password, verifyCode);

        });
    }


    /**
     * 注册方法
     * @param account  用户名
     * @param password  密码
     * @param verifyCode 验证码
     */
    private void doRegist(String account, String password, String verifyCode) {
        HashMap<String, String> body = new HashMap<>();
        body.put("account", account);
        body.put("password", password);
        body.put("verify_code", verifyCode);
        HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
        httpUtil.get(Url.REGIST, body, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = res.body().string();
                runOnUiThread(() -> {
                    ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resultStr, String.class);
                    if (resultBean.getCode().equals(200)) {
                        //Utils.showToastSync("注册成功");
                        // 返回上一个界面
//                        handler.post(() -> {
//                            Utils.showToast("注册成功");
//                            finish();
//                        });
                        Utils.showToast("注册成功");
                        finish();

                    } else {
                        failed(new IOException(resultBean.getMsg()));
                    }
                });

            }

            @Override
            public void failed(IOException e) {
                runOnUiThread(() -> {
                    Utils.showToast(e.getMessage());
                });

            }
        });
    }

    @Override
    protected void onDestroy() {
        mCountDownHelper.cancel();
        super.onDestroy();
    }
}